﻿// See https://aka.ms/new-console-template for more information
using System;
using System.ComponentModel;
using System.Net;
using System.Text;

var ver = $"https://gitee.com/ypeuee/MouseKeyMacro.Simple.Publish/raw/master/version ";
var file = $"https://gitee.com/ypeuee/MouseKeyMacro.Simple.Publish/raw/master/bbbb.zip ";
//var vvv=DownloadString(file);


//Main(ver, "aaaaa.zip");
WebCDownloadFile(ver, "aaaaa.zip");
//GetFile(file);




void WebCDownloadFile(string url, string filepath)
{
    try
    {
        using (var client = new WebClient())
        {
            client.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadCompleted);
            client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressChanged);

            client.DownloadFileAsync(new Uri(url), filepath);
        }
    }
    catch (Exception ex)
    {
        //处理异常
    }
}

void DownloadCompleted(object sender, AsyncCompletedEventArgs e)
{
    //下载完成后的处理
}

void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    //更新ProgressBar控件
}

void DownloadFile(string url, string filepath)
{
    try
    {
        var request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "GET";

        request.BeginGetResponse((result) =>
        {
            try
            {
                var response = (HttpWebResponse)request.EndGetResponse(result);


                using (var stream = response.GetResponseStream())
                using (var fileStream = new FileStream(filepath, FileMode.CreateNew))
                {
                    byte[] buffer = new byte[1024];
                    int bytesRead = 0;

                    while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        fileStream.Write(buffer, 0, bytesRead);
                    }
                }

                //BeginInvoke((Action)(() =>
                //{
                //    //下载完成后的处理代码
                //}));
            }
            catch (Exception ex)
            {
                //处理异常
            }
        }, null);
    }
    catch (Exception ex)
    {
        //处理异常
    }
}


async void Main(string fileUrl, string destinationFilePath)
{
    //string fileUrl = "http://example.com/file.pdf";
    //string destinationFilePath = "path/to/destination/file.pdf";


    // 创建HttpClient实例
    using (HttpClient client = new HttpClient())
    {
        // 发送GET请求并获取响应流
        using (HttpResponseMessage response = await client.GetAsync(fileUrl, HttpCompletionOption.ResponseHeadersRead))
        using (Stream contentStream = await response.Content.ReadAsStreamAsync())
        {
            // 获取文件总大小
            long? totalBytes = response.Content.Headers.ContentLength;

            // 创建目标文件流
            using (FileStream destinationStream = new FileStream(destinationFilePath, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                byte[] buffer = new byte[4096];
                long totalBytesRead = 0;
                int bytesRead;
                while ((bytesRead = await contentStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                {
                    // 写入目标文件
                    await destinationStream.WriteAsync(buffer, 0, bytesRead);

                    // 更新进度条
                    totalBytesRead += bytesRead;
                    if (totalBytes.HasValue)
                    {
                        int progressPercentage = (int)((totalBytesRead * 100) / totalBytes.Value);

                    }

                    // 可以在这里添加其他处理逻辑，比如取消按钮的检查

                    // 模拟一些延迟，以便能够看到进度条的更新
                    await System.Threading.Tasks.Task.Delay(100);
                }
            }
        }
    }

    Console.WriteLine("文件下载完成");
    Console.ReadLine();
}


static string DownloadString(string url)
{
    WebClient wc = new WebClient();
    //wc.BaseAddress = url;   //设置根目录
    wc.Encoding = Encoding.UTF8;    //设置按照何种编码访问，如果不加此行，获取到的字符串中文将是乱码
    string str = wc.DownloadString(url);



    return str;
}

//System.IO.File.WriteAllText($"c:\\{filePath}", GetFile(file));

System.Console.ReadKey();




static string GetFile(string input)
{
    var output = string.Empty;
    HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create(input);

    //request.Headers.Add("Authorization", githubtoken);
    request.AllowAutoRedirect = true;

    var response = (HttpWebResponse)request.GetResponse();

    using (var stream = new System.IO.MemoryStream())
    {
        response.GetResponseStream().CopyTo(stream);
        output = System.Text.Encoding.ASCII.GetString(stream.ToArray());
    }

    response.Close();

    return output;
}